package com.sunq.studio.sys.controller;

import com.sunq.studio.sys.domain.TbSysBookOrder;
import com.sunq.studio.sys.service.PayService;
import com.sunq.studio.sys.vo.PayVo;
import com.sunq.studio.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * Created by sunq on 2019/7/24.
 */

@Controller
@RequestMapping("/pay")
public class WXPayController {


    @Autowired
    PayService payService;


    static Logger logger= LoggerFactory.getLogger(WXPayController.class);
    @ResponseBody
    @RequestMapping("/wxPay")
    public ResultObjVO wxPay(HttpServletRequest request, HttpServletResponse response){

        String data="";
        try {
            InputStream in=request.getInputStream();
            BufferedReader br = new BufferedReader( new InputStreamReader( in ,"UTF-8"));//request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            //sb为微信返回的xml
            data = sb.toString();
            logger.info("wxPay data=[{}]",data);

        } catch (IOException e) {
            e.printStackTrace();
        }

        PayVo payVo=null;
        try {
            OtherPojo ob = JsonToOtherUtil.rtOtherPojo(data, new PayVo());
            payVo = (PayVo) ob.getObj();
        }catch (Exception e){
            return ResultUtil.error("500","参数异常");
        }
            payVo.setSpbillCreateIp(PayUtils.getIpAddr(request));
            payVo.setPayOrderId((new Date()).getTime() + "");

            Map res = PayUtils.WXpayOrder(payVo);

            if (res.containsKey("return_msg")) {


                return ResultUtil.error("500", (String) res.get("return_msg"));
            } else {
                TbSysBookOrder tbSysBookOrder = new TbSysBookOrder();
                tbSysBookOrder.setGoodId(0000);
                tbSysBookOrder.setOrderStatus(1);
                tbSysBookOrder.setOrderTime(new Date());
                tbSysBookOrder.setPayMoney(new BigDecimal(payVo.getPayMoney()));
                tbSysBookOrder.setPayBookId(payVo.getPayOrderId());
                tbSysBookOrder.setAddressId(0);
                tbSysBookOrder.setUserId(payVo.getUserId());
                tbSysBookOrder.setIpAddr(payVo.getSpbillCreateIp());
                tbSysBookOrder.setContents(payVo.getBody());

                payService.Save(tbSysBookOrder);
                return ResultUtil.success(res);
            }




    }
    @ResponseBody
    @RequestMapping("/wxPayCancel")
    public ResultObjVO wxPayCancel(HttpServletRequest request, HttpServletResponse response){

        String data="";
        try {
            InputStream in=request.getInputStream();
            BufferedReader br = new BufferedReader( new InputStreamReader( in ,"UTF-8"));//request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            //sb为微信返回的xml
            data = sb.toString();
            logger.info("wxPay data=[{}]",data);

        } catch (IOException e) {
            e.printStackTrace();
        }

        PayVo payVo=null;
        try {
            OtherPojo ob = JsonToOtherUtil.rtOtherPojo(data, new PayVo());
            payVo = (PayVo) ob.getObj();
            TbSysBookOrder tbSysBookOrder = new TbSysBookOrder();
            tbSysBookOrder.setUserId(payVo.getUserId());

            payService.notifyFail(tbSysBookOrder);
        }catch (Exception e){
            return ResultUtil.error("500","参数异常");
        }


        return null;
    }


    @PostMapping("/wxcallback")
    public void wxcallback(HttpServletRequest request, HttpServletResponse response){
        String resXml="";
        try {
            InputStream in=request.getInputStream();
            try {
                Map map=  PayUtils.wxNotify(in);

                String returnCode = (String) map.get("return_code");

                logger.info(returnCode);
                if ("SUCCESS".equals(returnCode)) {
//                    //验证签名是否正确
//                    Map<String, String> validParams = PayUtils.paraFilter(map);
//                    //回调验签时需要去除sign和空值参数
//
//                    String prestr = PayUtils.createLinkString(validParams);
//                    logger.info("prestr=="+prestr);
//                    //根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
//                    if (PayUtils.verify(prestr, (String) map.get("sign"), WxConfig.key, "utf-8")) {
                        /**此处添加自己的业务逻辑代码start**/
                        logger.info("wxnotify success!");
                        //注意要判断微信支付重复回调，支付成功后微信会重复的进行回调


                        payService.notifySuccess(map);

                        /**此处添加自己的业务逻辑代码end**/
                        //通知微信服务器已经支付成功
                        resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                 // /  }
                } else {
                    try{
                        payService.notifyFail(map);
                    }catch (Exception e){

                    }

                    resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                }

                BufferedOutputStream out = new BufferedOutputStream( response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
